package com.zhijiang.hospital.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zhijiang.config.webConfig.PassToken;
import com.zhijiang.hospital.entity.Checkin;
import com.zhijiang.hospital.entity.MedicalTechnollogy;
import com.zhijiang.hospital.entity.dto.FinOpbFeedetailDto;
import com.zhijiang.hospital.mapper.CheckinMapper;
import com.zhijiang.hospital.mapper.ComDeptBedsnumMapper;
import com.zhijiang.hospital.mapper.InpatientOperationDataMapper;
import com.zhijiang.hospital.mapper.OutpatientExaminationsMapper;
import com.zhijiang.hospital.service.FinOpbFeedetailDtoService;
import com.zhijiang.hospital.service.MedicalTechnologyService;
import com.zhijiang.util.HttpUtil;
import com.zhijiang.util.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.task.SimpleAsyncTaskExecutor;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 75936
 * @version 1.0
 * @project zhijiang_hospital_data
 * @description
 * @date 2023-01-13 08:11:15
 */
@Component("Task")
@EnableScheduling
@EnableAsync
@Slf4j
public class TaskController {
    /**
     * 异步线程池设置
     * 如果所有的任务都使用异步，线程池执行的话，可以不配置同步任务线程池。但是使用异步需要注意的是异步线程池的大小配置。异步的线程池默认是无上限的开启线程数的。
     *
     * @return
     */
    @Bean
    SimpleAsyncTaskExecutor simpleAsyncTaskExecutor() {
        SimpleAsyncTaskExecutor simpleAsyncTaskExecutor = new SimpleAsyncTaskExecutor();
        simpleAsyncTaskExecutor.setConcurrencyLimit(7);        //设置最大并行数
        simpleAsyncTaskExecutor.setDaemon(true);    //设置为守护线程
        return simpleAsyncTaskExecutor;
    }

    //    @Scheduled(fixedRate = 2000)
//    public void task1(){
//        System.out.println("task1运行"+ System.currentTimeMillis());
//    }
    @Autowired
    InpatientOperationDataMapper inpatientOperationDataMapper;
    @Autowired
    ComDeptBedsnumMapper comDeptBedsnumMapper;

    @Autowired
    OutpatientExaminationsMapper outpatientExaminationsMapper;

    @Autowired
    RedisService redisService;
    @Resource
    MedicalTechnologyService medicalTechnologyService;

    @Autowired
    FinOpbFeedetailDtoService findFinOpbFeedetailDtos;
    @Autowired
    CheckinMapper checkinMapper;


    //@Scheduled(cron ="0 0 0 * * ?")
    //@Scheduled(cron = "0 0/1 * * * ?")
    //@GetMapping("insertBedNum")
    //public void insertBedNum(){
    //    List<ComDeptBedsnum> all = comDeptBedsnumMapper.findAll();
    //    InpatientOperationData inpatientOperationData = new InpatientOperationData();
    //    for (ComDeptBedsnum deptBedsnum : all) {
    //        //System.out.println(deptBedsnum.getHospitalBed());
    //        inpatientOperationData.setId(RandomUtil.randomNumbers(10));
    //        inpatientOperationData.setDepartmentCode(deptBedsnum.getDeptCode());
    //        inpatientOperationData.setInpatientDepartment(deptBedsnum.getDeptName());
    //        inpatientOperationData.setHospitalBed(String.valueOf(deptBedsnum.getHospitalBed()));
    //        log.info("循环拿到的数据为"+deptBedsnum.getHospitalBed());
    //        System.out.println(inpatientOperationData.getInpatientDepartment()+"的数据"+String.valueOf(deptBedsnum.getHospitalBed()));
    //        inpatientOperationData.setCreateTime(new Date());
    //        System.out.println("定时任务"+deptBedsnum);
    //        //inpatientOperationDataMapper.addOneE(inpatientOperationData);
    //    }
    //}

    //@Scheduled(cron = "0 0/5 * * * ?")
    @GetMapping("test")
    public void FindOutpatientExaminations() {
        String endTime = DateUtil.formatDate(new Date());
        String startTime = DateUtil.formatDate(DateUtil.lastWeek());
        List<MedicalTechnollogy> weekData = outpatientExaminationsMapper.findWeekData(startTime, endTime);
        redisService.setStringKeyAndValue(startTime, weekData, 60);
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void findFinOpbFeedetailDtosLoadYearData() {
        List<FinOpbFeedetailDto> loadYearDataList = findFinOpbFeedetailDtos.loadYearData();
        List<FinOpbFeedetailDto> loadLastYearDataList = findFinOpbFeedetailDtos.loadLastYearData();
    }

    /***
     * @description:获取员工的打卡信息的定时任务
     * @author: JunFu
     * @date:
     * @param:
     * @return:
     **/
//    @GetMapping("load")
//    @PassToken

    //定时任务
    @Scheduled(cron = "0 0/20 * * * ?")
    //@Scheduled(cron = "0 0/2 * * * ?  ")
//    @Scheduled(fixedRate = 2000)
    public void getSignInInformation() {
        log.info("定时任务执行");
        List<String> idList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        String accessToken = JSONObject.parseObject(HttpUtil.get(HttpUtil.getToken)).getString("access_token");
        String accessToken1 = JSONObject.parseObject(HttpUtil.get(HttpUtil.getToken1 + HttpUtil.T)).getString("access_token");
        System.out.println(accessToken1);
        JSONArray userList = JSONObject.parseObject(HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/simplelist?fetch_child=1&department_id=43&access_token=" + accessToken)).getJSONArray("userlist");
        System.out.println(userList);
        for (int i = 0; i < userList.size(); i++) {
            JSONObject userData = userList.getJSONObject(i);
            String userid = userData.getString("userid");
            map.put(userid, userData.getString("name"));
            idList.add(userid);
        }
        JSONObject body = new JSONObject();
        for (int i = 0; i < idList.size(); i += HttpUtil.MAX_NUM) {
            List<String> userIdList = idList.subList(i, i + HttpUtil.MAX_NUM > idList.size() ? idList.size() : i + HttpUtil.MAX_NUM);
            body.put("opencheckindatatype", "3");
            body.put("starttime", DateUtil.beginOfDay(new Date()).getTime() / 1000);
            body.put("endtime", DateUtil.endOfDay(new Date()).getTime() / 1000);
            body.put("useridlist", userIdList);
            JSONObject jsonObject = JSONObject.parseObject(HttpUtil.doPost(HttpUtil.GetCheckinData + "?access_token=" + accessToken, body));
            JSONArray checkinData = jsonObject.getJSONArray("checkindata");
            for (int j = 0; j < checkinData.size(); j++) {
                Checkin checkin = new Checkin();
                checkin.setCode(IdWorker.getTimeId());
                JSONObject data = checkinData.getJSONObject(j);
                checkin.setUserid(data.getString("userid"));
                checkin.setClockType(data.getString("checkin_type"));
                checkin.setLocationDetail(data.getString("location_detail"));
                checkin.setLat(data.getString("lat"));
                checkin.setLng(data.getString("lng"));
                checkin.setName(map.get(data.getString("userid")));
                checkin.setCheckinTime(DateUtil.now());
                checkin.setLocationTitle(data.getString("location_title"));
                checkin.setCheckinDate(DateUtil.date(data.getLong("checkin_time") * 1000));
//                Integer integer = checkinMapper.get(checkin);
//                if (integer>=0){
//                    return;
//                }else {
//
//                }
                Integer integer = checkinMapper.get(checkin);
                if (integer < 1) {
                    checkinMapper.add(checkin);
                }
//                                if (integer>=0){
//                    return;
//                }else {
//                                    checkinMapper.add(checkin);
//                }

                //System.out.println("对象值:"+checkinData.get(j));
                //BeanUtils.copyProperties(checkin, checkinData.get(j));
                //if (!StringUtils.isEmpty(checkinData.get(j))){
                //    System.out.println(checkinData.get(j));
                //    Checkin user = JSONObject.parseObject( checkinData.get(j).toString(), Checkin.class);
                //    //System.out.println("user"+user);
                //    BeanUtils.copyProperties(user, checkin);
                //    //System.out.println("拿到的数据"+checkin);
                //}
                //BeanUtils.copyProperties(checkinData.get(j), checkin);
                //System.out.println("checkin"+checkin);
                //checkin.setCode(IdWorker.getTimeId());
                //JSONObject data = checkinData.getJSONObject(j);
                //checkin.setUserid(data.getString("userid"));
                //checkin.setType(data.getString("checkin_type"));
                //checkin.setLocationDetail(data.getString("location_detail"));
                //checkin.setLat(data.getString("lat"));
                //checkin.setLng(data.getString("lng"));
                //checkin.setName(map.get(data.getString("userid")));
                //checkin.setCheckinTime(DateUtil.now());
                //checkin.setLocationTitle(data.getString("location_title"));
                //checkin.setCheckinDate(DateUtil.date(data.getLong("checkin_time")*1000));
                //System.out.println(checkin);
            }
        }
    }

    public static void main(String[] args) {
        List<String> idList = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        String accessToken = JSONObject.parseObject(HttpUtil.get(HttpUtil.getToken)).getString("access_token");
        System.out.println(accessToken);
        JSONArray userList = JSONObject.parseObject(HttpUtil.get(HttpUtil.GetUserList + "?access_token=" + accessToken + "&department_id=1&fetch_child=1")).getJSONArray("userlist");
        System.out.println(userList);
        for (int i = 0; i < userList.size(); i++) {
            JSONObject userData = userList.getJSONObject(i);
            String userid = userData.getString("userid");
            map.put(userid, userData.getString("name"));
            idList.add(userid);
        }
        JSONObject body = new JSONObject();
        for (int i = 0; i < idList.size(); i += HttpUtil.MAX_NUM) {
            List<String> userIdList = idList.subList(i, i + HttpUtil.MAX_NUM > idList.size() ? idList.size() : i + HttpUtil.MAX_NUM);
            body.put("opencheckindatatype", "3");
            body.put("starttime", DateUtil.beginOfDay(new Date()).getTime() / 1000);
            body.put("endtime", DateUtil.endOfDay(new Date()).getTime() / 1000);
            body.put("useridlist", userIdList);
            JSONObject jsonObject = JSONObject.parseObject(HttpUtil.doPost(HttpUtil.GetCheckinData + "?access_token=" + accessToken, body));
            JSONArray checkinData = jsonObject.getJSONArray("checkindata");
            for (int j = 0; j < checkinData.size(); j++) {
                Checkin checkin = new Checkin();
                checkin.setCode(IdWorker.getTimeId());
                JSONObject data = checkinData.getJSONObject(j);
                checkin.setUserid(data.getString("userid"));
                checkin.setClockType(data.getString("checkin_type"));
                checkin.setLocationDetail(data.getString("location_detail"));
                checkin.setEndTime(new Date().toString());
                checkin.setLat(data.getString("lat"));
                checkin.setLng(data.getString("lng"));
                checkin.setName(map.get(data.getString("userid")));
                checkin.setCheckinTime(DateUtil.now());
                checkin.setLocationTitle(data.getString("location_title"));
                checkin.setCheckinDate(DateUtil.date(data.getLong("checkin_time") * 1000));
                System.out.println(checkin);
                //checkinMapper.add(checkin);

            }
        }
    }

}
